package com.frejoys.task;

import com.frejoys.common.util.CacheKeyUtil;
import com.frejoys.dao.entity.Order;
import com.frejoys.service.OrderService;
import com.frejoys.service.RebateService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

// 订单核销任务
@Component
@RequiredArgsConstructor
public class OrderVerifyTask {

    // @Scheduled(cron = "{秒数} {分钟} {小时} {日期} {月份} {星期}")

    private final RedissonClient redissonClient;

    private final OrderService orderService;

    private final RebateService rebateService;


    /**
     * 每3分钟，处理需要核销计算的订单
     * 将商品还原，订单失效
     */
    @Async
    // @Scheduled(cron = "0 */3 * * * ?")
    @Scheduled(cron = "0/5 * * * * ?")
    public void dispatchOrderVerify() {

        RLock lock = redissonClient.getLock(CacheKeyUtil.taskOrderVerifyLockKey());

        if (lock.tryLock()) {
            try {

                // 获取需要处理的核销计算订单
                List<Order> orders = orderService.getVerifyInProgressOrder(1, 1000);
                for (Order e : orders) {
                    rebateService.orderVerify(e.getId());
                }

            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        }

    }











}
